package org.shiro.demo.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.OrderBuffer;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IOrderBufferService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service("orderBufferService")
public class OrderBufferServiceImpl extends DefultBaseService implements IOrderBufferService {
	@Resource(name = "baseService")
	private IBaseService baseService;
	DateTimeFormatter dayFormat = DateTimeFormat.forPattern("yyyy-MM-dd");

	/**
	 * 根据 date跟 phone 找到 所有的 orderbuffer
	 * 
	 * @param phone
	 * @param date
	 * @return
	 */
	@Cacheable(value = "orderbuffer", key = "#date+'-'+#phone")
	public List<OrderBuffer> getAndCache(String phone, String date) {
		List<QueryCondition> list = new ArrayList<QueryCondition>();
		org.joda.time.DateTime bufferDate = DateTime.parse(date, dayFormat);
		list.add(new QueryCondition("bufferDate", QueryCondition.EQ, bufferDate.toDate()));
		list.add(new QueryCondition("operator", QueryCondition.EQ, phone));
		List<OrderBuffer> orderBuffers = baseService.get(OrderBuffer.class, list);
		return orderBuffers;
	}

	/**
	 * 更新orderbuffer
	 * 
	 * @param phone
	 * @param date
	 * @param orderBuffer
	 * @return
	 */
	@CacheEvict(value = "orderbuffer", key = "#date+'-'+#phone")
	public boolean saveAndCache(String phone, String date, OrderBuffer orderBuffer) {
		try {
			baseService.save(orderBuffer);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
